'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
import locale
from dopplershift.core.containers.mediator import DSMediatorSingleton
from dopplershift.core.containers.container import DSContainer
from dopplershift.collector.config import XMLCollectorConfig
from dopplershift.collector.routing.router import Router
from dopplershift.collector.resource import CollectorResource
from dopplershift.collector.templates import TemplateLoader
from dopplershift.core.utils.logger import DSLogging
from twisted.web import server
from twisted.internet import reactor
from dopplershift.core.app.cline import CommandLineApp
from dopplershift.collector.backends.auth.factory import authenticate_factory
from dopplershift.collector.backends.cache.factory import cache_factory
from dopplershift.collector.shell.factory import collector_shell_builder
from dopplershift.core.plugins.factory import PluginsFactory

class CollectorBuilder(CommandLineApp):
    config_class = XMLCollectorConfig
    router_class = Router
    resource_class = CollectorResource
    templates_loader = TemplateLoader
    __program__ = 'dscollector'
    __description__ = 'Doplershift Collector web site composition system'
    __arguments__ = (
                     {
                      'name': '--port',
                      'dest': 'port',
                      'type': int,
                      'help': 'service port number'
                      },
                     {
                      'name': '--host',
                      'dest': 'host',
                      'type': str,
                      'default': '0.0.0.0',
                      'help': 'service interface binding'
                      },
                     )
    def __init__(self):
        '''
        Building and mediating collector infrastructure
        '''
        CommandLineApp.__init__(self)
        self._config =  self._args.configfile
        self._port = self._args.port
        
        self._mediator = DSMediatorSingleton().get()
        config = self.config_class(self._config)
        self._mediator.register("CollectorConfig", config)
        self._mediator.register("AppConfig", config)
        
        system_locale = config.get("SYSTEM_LOCALE")
        if system_locale: 
            locale.setlocale(locale.LC_ALL, str(system_locale))
            #locale.setlocale(locale.LC_ALL, system_locale)
        router = self.router_class()
        self._mediator.register('CollectorRoutes', router)
        resource = self.resource_class()
        site = server.Site(resource)        
        self._mediator.register('CollectorSite', site)
        
        handlers = DSContainer()
        self._mediator.register("CollectorHandlers", handlers)
        
        requests = DSContainer()
        self._mediator.register("CollectorRequests", requests)
        
        self._plugins = PluginsFactory('collector.renderer')
        self._plugins.configure(config)
        self._mediator.register("PluginsFactory", self._plugins)
        
        default_renderer = config.get("default_collector_renderer")
        renderer = self._plugins.get(default_renderer, 'collector.renderer')
        self._mediator.register("ErrorRender", renderer)
        d = DSLogging(
                      config.get("logLevel")
                      )
        d.twistedObserver()
        

    def cleanRequestsStorage(self):
        '''

        '''
    def run(self):
        '''
        Running collector resources, http server and shedulers pools
        '''
        cb = cache_factory()
        ab = authenticate_factory()
        self._mediator.register("CacheBackend", cb)
        self._mediator.register("AuthBackend", ab)
        cb.run()
        ab.run()
        reactor.listenTCP(
                          self._port,
                          self._mediator.get('CollectorSite'),
                          interface=self._args.host
                          )
        
        collector_shell_builder(self._args.port)
        reactor.run()        